/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2022-09-29
 * Time: 21:58
 */
class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
         this.val = val;
         this.left = left;
      this.right = right;
     }
 }
public class isBalanced {
    public int maxHeight(TreeNode root){
        if(root==null){
            return 0;
        }
        int leftHeight=maxHeight(root.left);
        int rightHeight=maxHeight(root.right);
        if(leftHeight==-1||rightHeight==-1||Math.abs(leftHeight-rightHeight)>=2){
            return -1;
        }
        return (leftHeight>rightHeight)?leftHeight+1:rightHeight+1;
    }

    public boolean isBalanced(TreeNode root) {
        //注意可以等于0
        return maxHeight(root)>=0;
    }
}
